const mongoose = require('mongoose');

const medicineSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, '药品名称不能为空'],
    trim: true,
    maxlength: [50, '药品名称最多50个字符']
  },
  imageUrl: {
    type: String,
    default: ''
  },
  defaultImageUrl: {
    type: String,
    default: ''
  },
  efficacy: {
    type: String,
    required: [true, '功效不能为空'],
    maxlength: [500, '功效描述最多500个字符']
  },
  specification: {
    type: String,
    required: [true, '规格不能为空'],
    maxlength: [100, '规格描述最多100个字符']
  },
  productionDate: {
    type: Date,
    required: [true, '生产日期不能为空']
  },
  expiryDate: {
    type: Date,
    required: [true, '有效期不能为空']
  },
  remainingQuantity: {
    type: Number,
    required: [true, '剩余数量不能为空'],
    min: [0, '剩余数量不能小于0']
  },
  usage: {
    type: String,
    required: [true, '用法用量不能为空'],
    maxlength: [500, '用法用量描述最多500个字符']
  },
  precautions: [{
    type: String,
    maxlength: [200, '注意事项描述最多200个字符']
  }],
  categoryId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Category',
    required: [true, '分类不能为空']
  },
  status: {
    type: String,
    enum: ['normal', 'expired', 'nearExpiry'],
    default: 'normal'
  },
  userId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: [true, '用户ID不能为空']
  }
}, {
  timestamps: true
});

// 创建索引
medicineSchema.index({ name: 'text' });
medicineSchema.index({ userId: 1, categoryId: 1 });
medicineSchema.index({ expiryDate: 1 });

// 更新药品状态的方法
medicineSchema.methods.updateStatus = function() {
  const now = new Date();
  const expiryDate = new Date(this.expiryDate);
  const thirtyDaysFromNow = new Date(now.getTime() + (30 * 24 * 60 * 60 * 1000));

  if (expiryDate < now) {
    this.status = 'expired';
  } else if (expiryDate <= thirtyDaysFromNow) {
    this.status = 'nearExpiry';
  } else {
    this.status = 'normal';
  }
};

// 保存前更新状态
medicineSchema.pre('save', function(next) {
  this.updateStatus();
  next();
});

const Medicine = mongoose.model('Medicine', medicineSchema);

module.exports = Medicine;